#pragma once
#include <PubSubClient.h>
#include <ArduinoJson.h>

WiFiClient esp32Client;
PubSubClient mqttClient(esp32Client);

// void parseInfo(String data);  // JSON数据解析
void connectMQTTServer();

/*订阅主题*/
void subscribeTopic()
{
    if (mqttClient.subscribe(APP_ESP32))
    {
        Serial.print(F("Subscribed Topic: "));
        Serial.println(APP_ESP32);
    }
    else
    {
        Serial.print(F("Subscribe Fail..."));
    }
}

void receiveCallback(char *topic, byte *payload, unsigned int length)
{
    String data = "";
    for (int i = 0; i < length; i++)
    {
        data += (char)payload[i];
    }
    // parseInfo(data); // 解析数据
}

void MQTT(void *pt)
{
    mqttClient.setServer(mqttServer, 1883);
    connectMQTTServer();
    mqttClient.setCallback(receiveCallback); // 订阅主题的回调函数
    while (1)
    {
        mqttClient.loop();
    }
}

void connectMQTTServer()
{
    while (!mqttClient.connected())
    {
        if (mqttClient.connect(clientId, mqttUserName, mqttPwd))
        {
            Serial.println(F("MQTT connected"));
            // subscribeTopic(); // 连接成功后，订阅主题
        }
        else
        {
            Serial.print(F("failed, rc="));
            Serial.print(mqttClient.state());
            Serial.println(F(" try again in 5 seconds"));
            vTaskDelay(5000);
        }
    }
}

// void parseInfo(String data)
// {
//     /*JSON数据解析*/
//     const size_t capacity = JSON_OBJECT_SIZE(1) + 10;
//     DynamicJsonBuffer jsonBuffer(capacity);
//     const char *json = data.c_str();
//     JsonObject &root = jsonBuffer.parseObject(json);
//     int msg = root["msg"]; // 2
//     /*根据JSON信息执行相应的动作*/
//     switch (msg)
//     {
//     case 1:
//         Serial.println("LED_on");
//         break;
//     case 2:
//         Serial.println("LED_off");
//         break;
//     default:
//         break;
//     }
// }